
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using Yozeev.SystemConfig;
using Yozeev.SystemConfig.Dtos;
using Yozeev.SystemConfig.DomainService;
using Yozeev.SystemConfig.Authorization;
using Yozeev.Common;

namespace Yozeev.SystemConfig
{
    /// <summary>
    /// PowerRole应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class PowerRoleAppService : YozeevAppServiceBase, IPowerRoleAppService
    {
        private readonly IRepository<PowerRole, Guid> _entityRepository;

        private readonly IPowerRoleManager _entityManager;

        private readonly IRepository<Power, Guid> _powerRepository;

        private readonly IQueryHelper _queryHelper;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public PowerRoleAppService(
        IRepository<PowerRole, Guid> entityRepository
        ,IPowerRoleManager entityManager
            , IRepository<Power, Guid> powerRepository
            , IQueryHelper queryHelper
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _powerRepository = powerRepository;
            _queryHelper = queryHelper;
        }


        /// <summary>
        /// 获取PowerRole的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<PowerRoleListDto>> GetPaged(GetPowerRolesInput input)
		{

            var expression = _queryHelper.WhereExp<PowerRole>(input.queryData);
            var query = from entity in _entityRepository.GetAll().AsNoTracking()
                        .Where(expression)
                        select new
                        {
                            entity,
                            entity.Power,
                            entity.Role
                        };
            var list = new List<PowerRole>();
            query.ToList().ForEach(temp => {
                var _entity = temp.entity;
                _entity.Power = temp.Power;
                _entity.Role = temp.Role;
                list.Add(_entity);
            });
            // TODO:根据传入的参数添加过滤条件


            var count = list.Count();
            var entityList = list;

            // var entityListDtos = ObjectMapper.Map<List<PowerRoleListDto>>(entityList);
            var entityListDtos =entityList.MapTo<List<PowerRoleListDto>>();

			return new PagedResultDto<PowerRoleListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取PowerRoleListDto信息
		/// </summary>
		public async Task<PowerRoleListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<PowerRoleListDto>();
		}

		/// <summary>
		/// 获取编辑 PowerRole
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetPowerRoleForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetPowerRoleForEditOutput();
PowerRoleEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<PowerRoleEditDto>();

				//powerRoleEditDto = ObjectMapper.Map<List<powerRoleEditDto>>(entity);
			}
			else
			{
				editDto = new PowerRoleEditDto();
			}

			output.PowerRole = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改PowerRole的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdatePowerRoleInput input)
		{

			if (input.PowerRole.Id.HasValue)
			{
				await Update(input.PowerRole);
			}
			else
			{
				await Create(input.PowerRole);
			}
		}


		/// <summary>
		/// 新增PowerRole
		/// </summary>
		protected virtual async Task<PowerRoleEditDto> Create(PowerRoleEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <PowerRole>(input);
            var entity=input.MapTo<PowerRole>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<PowerRoleEditDto>();
		}

		/// <summary>
		/// 编辑PowerRole
		/// </summary>
		protected virtual async Task Update(PowerRoleEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除PowerRole信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除PowerRole的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


        /// <summary>
        /// 导出PowerRole为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        //public async Task<FileDto> GetToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}

        /// <summary>
        /// 根据角色ID修改权限
        /// </summary>
		/// <param name="RoleId">角色ID</param>
		/// <param name="PowerIdList">权限ID列表</param>
		/// <returns></returns>
        public async Task BatchAddOrUpdate(int RoleId,List<Guid> PowerIdList)
        {
            //删除
            await _entityRepository.DeleteAsync(s => s.RoleId == RoleId);
            //添加
            foreach(var powerId in PowerIdList)
            {
                var powerRole = new PowerRole()
                {
                    PowerId = powerId,
                    RoleId = RoleId,
                    CreationTime = DateTime.Now,
                    CreatorUserId = AbpSession.UserId,
                };
                await _entityRepository.InsertAndGetIdAsync(powerRole);
            }
        }
        /// <summary>
        /// 根据角色ID查询权限信息
        /// IsCheck表示是否勾选
        /// </summary>
        /// <param name="RoleId">角色ID</param>
        /// <returns></returns>
        public async Task<PagedResultDto<PowerListDto>> GetPowerRoleListById(int RoleId)
        {
            var query = from power in _powerRepository.GetAll()
                        select new PowerListDto
                        {
                            MenuId = power.MenuId,
                            Menu = power.Menu,
                            MenuPath = power.MenuPath,
                            PowerCode = power.PowerCode,
                            PowerName = power.PowerName,
                            Method = power.Method,
                            Params = power.Params,
                            GroupName = power.GroupName,
                            Sort = power.Sort,
                            IocName = power.IocName,
                            IocClassName = power.IocClassName,
                            Category = power.Category,
                            IsEnabled = power.IsEnabled,
                            CreationTime = power.CreationTime,
                            CreatorUserId = power.CreatorUserId,
                            Id = power.Id,
                            IsCheck = false,
                        };
            var list = query.ToList();
            var powerRoleList = _entityRepository.GetAll().Where(p => p.RoleId == RoleId).Select(p=>p.PowerId).ToArray();
            list.Where(power => powerRoleList.Contains(power.Id)).ToList().ForEach(power => {
                power.IsCheck = true;
            });
            var count = list.Count;


            return new PagedResultDto<PowerListDto>(count, list);
        }
    }
}


